package com.example.agricultural_big_data.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.agricultural_big_data.service.VerificationCodeService;
import com.example.agricultural_big_data.util.LoginRequired;
import com.example.agricultural_big_data.util.RedisUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author xiao yang
 * @Description: 图形验证码
 * @date 2021/3/913:18
 */
@RestController
@CrossOrigin
@RequestMapping("/image")
public class VerificationCodeController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private VerificationCodeService verificationCodeService;

    //获取图形验证码
    @LoginRequired
    @RequestMapping(value = "/getimage")
    public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {

        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            request.getSession().setAttribute("verifyCode", createText);
            redisUtil.set(createText, createText, 500);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException | IOException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    //图形验证码的检验
    @LoginRequired
    @RequestMapping("/verifyCode")
    public Object imgverifyControllerDefaultKaptcha(@RequestBody JSONObject jsonObject) {
        return verificationCodeService.verficationCode(jsonObject);
    }

}
